package com.runa.rccprotocol.dto.guangda;

import com.runa.monitor.comm.dto.newComm.HotMeterVO;
import com.runa.monitor.comm.dto.newComm.ValveVO;
import com.runa.persistence.CollectionUtil;
import com.runa.persistence.DateUtil;
import com.runa.persistence.service.LogService;
import com.runa.protocol.dto.DtuReport;
import com.runa.protocol.enums.ByteOrder;
import com.runa.protocol.util.ByteUtil;
import com.runa.protocol.util.UtilTime;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 2024/7/3 10:53
 * zhangYB
 */
@Data
@Slf4j
public class GdFrameSequence {

    private static byte startSymbol = 0x68;

    private static Integer frameLength = 64;


    public GdFrameSequence() {
    }

    public void analysisMultiEqu(GdConcentratorResponseData response, byte[] controlData) {

    }

    public void analysisOneEqu(GdConcentratorResponseData response, byte[] controlData) {

    }


    public List<ValveVO> analysisValve(byte[] data, int begin, int length) {
        List<ValveVO> valveVOList = new ArrayList<>();
        for (int i = begin; i < length; i++) {
            if (data[i] == startSymbol && data[i+1] == 0x20) {
                i += 2;
                String serial = String.valueOf(Long.valueOf(ByteUtil.bcd2str(data, i, 7, false)));
                try {
                    i += 7;
                    ValveVO valveVO = new ValveVO();
                    valveVO.setValveSerial(serial);
                    i += 1;
                    int len = data[i] & 0xff;
                    if (len < 46) {
                        continue;
                    }
                    i += 1;
                    byte[] bytes = ByteUtil.byteSubByte(ByteUtil.slice(data, i, len), (byte) 0x33);
                    i += len;
                    log.debug("{}: {}", serial, ByteUtil.byteToHexString(bytes));

                    if (!(bytes[0] == (byte)0x90 && bytes[1] == (byte)0x1f)) {
                        continue;
                    }
                    int index = 4;

                    index += 5;

                    index += 5;

                    index += 5;

                    index += 5;

                    index += 4;

                    index += 3;

                    index += 3;

                    index += 3;
                    String s = ByteUtil.byteToHexStringFlip(bytes, index, 7);
                    if (!"00000000000000".equals(s)) {
                        valveVO.setValveDate(DateUtil.stringToDate(s, DateUtil.NO_LINE_FORMAT));
                    }
                    index += 7;
                    int valveStatus = bytes[index] & 0x03;
                    if (valveStatus == 0) {
                        valveVO.setActOpen((float)100);
                    } else if (valveStatus == 1) {
                        valveVO.setActOpen((float)0);
                    } else if (valveStatus == 3) {
                    }
                    valveVOList.add(valveVO);
                } catch (Exception e) {
                    log.error("{} analysisMeter 光大: {}", serial, e.getMessage());
                    log.debug("{} 光大: {}", serial, e);
                }
            }
        }
        List<ValveVO> valveVOS = valveVOList.stream().filter(v -> null != v.getValveDate()).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(valveVOS)) {
            valveVOS.sort(Comparator.comparing(ValveVO::getValveDate));
            valveVOList = valveVOS;
        }
        return valveVOList;
    }

    public List<HotMeterVO> analysisMeter(byte[] data, int begin, int length) {
        List<HotMeterVO> hotMeterList = new ArrayList<>();
        for (int i = begin; i < length; i++) {
            if (data[i] == startSymbol && data[i+1] == 0x20) {
                i += 2;
                String serial = String.valueOf(Long.valueOf(ByteUtil.bcd2str(data, i, 7, false)));
                try {
                    i += 7;
                    HotMeterVO hotMeterVO = new HotMeterVO();
                    hotMeterVO.setMeterSerial(serial);
                    i += 1;
                    int len = data[i] & 0xff;
                    if (len < 46) {
                        continue;
                    }
                    i += 1;
                    byte[] bytes = ByteUtil.byteSubByte(ByteUtil.slice(data, i, len), (byte) 0x33);
                    i += len;
                    log.debug("{}: {}", serial, ByteUtil.byteToHexString(bytes));

                    if (!(bytes[0] == (byte)0x90 && bytes[1] == (byte)0x1f)) {
                        continue;
                    }
                    int index = 4;
                    float accCold = (float) (Float.valueOf(ByteUtil.bcd2str(bytes, index, 4, false)) * 0.01);

                    index += 5;
                    float accHeat = (float) (Float.valueOf(ByteUtil.bcd2str(bytes, index, 4, false)) * 0.01);
                    hotMeterVO.setAccHeat(accHeat);

                    index += 5;
                    float power = (float) (Float.valueOf(ByteUtil.bcd2str(bytes, index, 4, false)) * 0.01);
                    hotMeterVO.setPower(power);

                    index += 5;
                    float flow = (float) (Float.valueOf(ByteUtil.bcd2str(bytes, index, 4, false)) * 0.0001);
                    if (flow > 1000) {
                        flow = -1;
                    }
                    hotMeterVO.setFlow(flow);

                    index += 5;
                    float accFlow = (float) (Float.valueOf(ByteUtil.bcd2str(bytes, index, 4, false)) * 0.01);
                    hotMeterVO.setAccFlow(accFlow);

                    index += 4;
                    float supplyTemp = (float) (Float.valueOf(ByteUtil.bcd2str(bytes, index, 3, false)) * 0.01);
                    if (supplyTemp > 200) {
                        supplyTemp = (float) ((supplyTemp * 100 - 967200) * 0.01);
                    }
                    hotMeterVO.setSupplyTemp(supplyTemp);

                    index += 3;
                    float returnTemp = (float) (Float.valueOf(ByteUtil.bcd2str(bytes, index, 3, false)) * 0.01);
                    if (returnTemp > 200) {
                        returnTemp = (float) ((returnTemp * 100 - 967200) * 0.01);
                    }
                    hotMeterVO.setReturnTemp(returnTemp);

                    index += 3;
                    String workTime = ByteUtil.bcd2str(bytes, index, 3, false);
                    hotMeterVO.setWorkTime(Integer.valueOf(workTime));

                    index += 3;
                    String s = ByteUtil.byteToHexStringFlip(bytes, index, 7);
                    if (!"00000000000000".equals(s)) {
                        hotMeterVO.setMeterDate(DateUtil.stringToDate(s, DateUtil.NO_LINE_FORMAT));
                    }
                    hotMeterList.add(hotMeterVO);
                } catch (Exception e) {
                    log.error("{} analysisMeter 光大: {}", serial, e.getMessage());
                    log.debug("{} 光大: ", serial, e);
                }
            }
        }
        List<HotMeterVO> hotMeterVOS = hotMeterList.stream().filter(v -> null != v.getMeterDate()).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(hotMeterVOS)) {
            hotMeterVOS.sort(Comparator.comparing(HotMeterVO::getMeterDate));
            hotMeterList = hotMeterVOS;
        }
        return hotMeterList;
    }

    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = UtilTime.StringToDate("241201000000", "yyMMddHHmmss");
        Date date3 = UtilTime.StringToDate("241202000000", "yyMMddHHmmss");
        Date date4 = UtilTime.StringToDate("241201010203", "yyMMddHHmmss");
        List<Date> dates = Arrays.asList(date1, date2, date3, date4);
        System.out.println(dates);
        dates.sort(Comparator.comparing(d -> d));
        System.out.println(dates);
    }

}
